package ink.tsg.export.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName SplitPDFUtils.java
 * @Description 拆分pdf
 * @createTime 2021-08-12
 */
public class SplitPDFUtils {

    public static void main(String[] args) {
        toImage(new File("E:\\工作文档\\OpenCV-Python-Tutorial-中文版.pdf"));
    }

    /***
     * 指定页数的PDF文件转换为图片：
     */
    public static void toImage(File inputStream) {
        PDDocument pdDocument = null;
        /* dpi越大转换后越清晰，相对转换速度越慢 */
        int dpi = 100;
        try {
            pdDocument = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int pages = pdDocument.getNumberOfPages();
//            BufferedImage watermarkImage = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
//            Graphics2D graphics = watermarkImage.createGraphics();
//            graphics.setColor(Color.RED);
//            graphics.
//            graphics.drawString("geomative",20,20);
            for (int i = 0; i < pages; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                Graphics2D graphics2D = image.createGraphics();
                graphics2D.setColor(Color.lightGray);
                graphics2D.setFont(new Font("Monospaced", Font.ITALIC, 40));
                for(int j = 0;j<image.getWidth();j+=60){
                    graphics2D.drawString("赛盈地脉版权所有",j,j+=60);
                }
                ImageIO.write(image, "PNG", new FileOutputStream(new File("D:\\tmp\\pdf\\" + i + ".png")));
            }

//            if (page <= pages && page >= 0) {
//                BufferedImage image = renderer.renderImageWithDPI(page, dpi);
//                ImageIO.write(image, imgType, sos);
//            }
        } catch (Exception e) {
//            logger.error(e.getMessage());
        } finally {
            if (pdDocument != null) {
                try {
                    pdDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
